package com.jzo2o.foundations.service.impl;

import cn.hutool.json.JSONUtil;
import com.jzo2o.foundations.model.domain.ServeSearch;
import com.jzo2o.foundations.service.IESService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: liZhiJun
 * @CreateTime: 2025-09-24
 * @Description: ES 服务实现类
 * @Version: 1.0
 */
@Slf4j
@Service
public class IESServiceImpl implements IESService {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 搜索
     *
     * @param cityCode    城市代码
     * @param keyword     关键字
     * @param serveTypeId 服务类型id
     * @return 搜索结果
     */
    @Override
    public List<ServeSearch> search(String cityCode, String keyword, String serveTypeId) {
        //1，创建请求
        SearchRequest searchRequest = new SearchRequest("serve");
        //2，创建构造请求
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (StringUtils.hasText(keyword)) {
            boolQuery.must(QueryBuilders.multiMatchQuery(keyword, "serveItemName", "serveTypeName"));
        } else if (serveTypeId != null) {
            boolQuery.filter(QueryBuilders.matchAllQuery());
        }

        if (cityCode != null) {
            boolQuery.filter(QueryBuilders.termQuery("cityCode", cityCode));
        }
        if (StringUtils.hasText(serveTypeId)) {
            boolQuery.filter(QueryBuilders.termQuery("serveTypeId", serveTypeId));
        }
        //3，执行查询
        searchRequest.source().query(boolQuery);
        List<ServeSearch> serveSearches = new ArrayList<>();
        try {
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = response.getHits();
            SearchHit[] hitsHits = hits.getHits();
            for (SearchHit hit : hitsHits) {
                //转为对象ServeSearch
                ServeSearch serveSearch = JSONUtil.toBean(hit.getSourceAsString(), ServeSearch.class);
                serveSearches.add(serveSearch);
            }

        } catch (IOException e) {
            log.error("搜索失败", e);
        }
        return serveSearches;
    }
}
